package com.itao.xstream;

import com.itao.bean.Clazz;
import com.itao.bean.School;
import com.itao.bean.Student;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.AnyTypePermission;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Collections;

/**
 * @Author sjt
 * @CreateTime 2023/10/15 15:10
 */
public class XstreamTest {

    public static void main(String[] args) throws Exception{
        read();
        //write();
    }

    private static void read(){
        var xStream = new XStream();
        xStream.addPermission(AnyTypePermission.ANY);
        xStream.setClassLoader(XstreamTest.class.getClassLoader());
        xStream.processAnnotations(new Class[]{School.class, Clazz.class, Student.class});

        var School = (School)xStream.fromXML(new File("D:\\workspace\\idea\\java-learn\\xml\\src\\main\\resources\\read.xml"));
        System.out.println(School);
    }

    private static void write() throws Exception{
        var school = new School();

        var aClass = new Clazz();
        aClass.setNo("1801");
        school.setClazz(Collections.singletonList(aClass));

        var student = new Student();
        student.setNo("1");
        student.setName("张鹏飞");
        student.setSex("男");
        student.setAddr("武汉");
        aClass.setStudents(Collections.singletonList(student));

        var xStream = new XStream();
        xStream.setClassLoader(XstreamTest.class.getClassLoader());
        xStream.processAnnotations(new Class[]{School.class, Clazz.class, Student.class});
        try (var os = new FileOutputStream("D:\\workspace\\idea\\java-learn\\xml\\src\\main\\resources\\xstream-write.xml")){
            xStream.toXML(school, os);
        }
    }
}
